'use strict';

const Controller = require('egg').Controller;

class BankController extends Controller {

    //银行卡 新增 编辑
    async edit() {
        const { ctx, app } = this
        const uid = ctx.wxUser.id
        ctx.validate({
            id: {
                type: 'int',
                required: false,
                desc: 'id'
            },
            bankconfig_id: {
                type: 'int',
                required: true,
                desc: '银行卡配置id'
            },
            name: {
                type: 'string',
                required: true,
                desc: '持卡人姓名'
            },
            code: {
                type: 'int',
                required: true,
                desc: '卡号'
            },
            bank_branch: {
                type: 'string',
                required: true,
                desc: '支行名称'
            }
        })
        const { id, bankconfig_id, name, code, bank_branch } = ctx.request.body
        let listTwo = await app.model.BankConfig.findByPk(bankconfig_id)
        if (!listTwo) {
            ctx.throw(400, '银行卡配置id不存在')
        }
        let list
        if (id == 0) {//新增
            list = await app.model.Bank.create({ bankconfig_id, name, code, bank_branch, type: 'wxuser', type_id: uid })
        } else {
            let listone = await app.model.Bank.findByPk(id)
            if (!listone) {
                ctx.throw(400, '银行卡id不存在')
            }
            list = await listone.update({ bankconfig_id, name, code, bank_branch, type: 'wxuser', type_id: uid })
        }
        ctx.apiSuccess(list)
    }
    //银行卡 列表
    async list() {
        const { ctx, app } = this
        const uid = ctx.wxUser.id
        let list = await ctx.page(app.model.Bank, { type_id: uid }, {
            include: [
                {
                    model: app.model.BankConfig,
                    as: 'bankconfig',
                    attributes: ['title', 'logo', 'bg_image']
                }
            ]
        })
        ctx.apiSuccess(list)
    }
    //删除
    async del() {
        const { ctx, app } = this
        const uid = ctx.wxUser.id
        const id = ctx.params.id
        let list = await app.model.Bank.findOne({
            where: {
                id,
                type_id: uid
            }
        })
        if (!list) {
            ctx.throw(400, '银行卡不存在')
        }
        let aa = await list.destroy()
        if (!aa) {
            ctx.throw(400, '删除失败')
        }
        ctx.apiSuccess('删除成功')
    }
}

module.exports = BankController;
